<template>
  <div style="margin-bottom: 16px">
    <span style="margin-left: 8px">
      <template v-if="hasSelected">
        {{ `选中 ${state.selectedRowKeys.length} 条数据` }}
      </template>
    </span>
  </div>

  <a-table
      :data-source="courses"
      :columns="columns"
      row-key="courseId"
      :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
      bordered
  >
    <!-- 自定义渲染列模板 -->
    <template #image="{ record }">
      <img :src="record.image" alt="course image" style="width: 100px; height: auto;" />
    </template>
    <template #teacherAvatar="{ record }">
      <img :src="record.teacherAvatar" alt="teacher avatar" style="width: 40px; height: 40px; border-radius: 50%;" />
    </template>
    <template #action="{ record }">
      <a-space>
        <a-button :disabled="hasbutton" @click="managerChapter(record.courseId)" type="ghost" size="small">章节</a-button>
        <a-button :disabled="hasbutton" @click="editCourse(record)" type="primary" size="small">编辑</a-button>
        <a-button danger :disabled="hasbutton" @click="deleteCourse(record.courseId)" size="small">删除</a-button>

      </a-space>
    </template>
    <template #title>
      <div style="display: flex; justify-content: end">
        <a-space>
          <a-button danger type="primary" :disabled="!hasSelected" :loading="state.loading" @click="start">
            批量删除
          </a-button>
          <a-button type="primary" :disabled="hasbutton" @click="addCourse">添加课程</a-button>

        </a-space>
      </div>
    </template>
  </a-table>

  <!-- 编辑课程的模态框 -->
  <a-modal v-model:visible="isEditModalVisible" title="编辑课程" @ok="handleEdit" @cancel="closeEditModal">
    <a-form :model="updateCourse" labelAlign="right" layout="vertical">
      <a-form-item label="课程名称:">
        <a-input v-model:value="updateCourse.title">
          <template #prefix>
            <user-outlined style="color: rgba(0, 0, 0, 0.45)" />
          </template>
          <template #suffix>
            <a-tooltip title="额外信息">
              <info-circle-outlined style="color: rgba(0, 0, 0, 0.45)" />
            </a-tooltip>
          </template>
        </a-input>
      </a-form-item>
      <a-form-item label="课程分类:">
        <a-select v-model:value="updateCourse.categoryId" placeholder="请输入分类:">
          <a-select-option v-for="category in categoryOptions" :value="category.categoryId">
            {{ category.categoryName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="课程价格:">
        <a-input v-model:value="updateCourse.price" placeholder="请输入价格:" prefix="￥" suffix="RMB" />
      </a-form-item>
      <a-form-item label="课程描述:">
        <a-textarea v-model:value="updateCourse.description" placeholder="请输入课程描述:" />
      </a-form-item>
      <a-form-item label="课程图片:">
        <a-textarea v-model:value="updateCourse.image" placeholder="请输入课程图片链接:" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 确认删除的模态框 -->
  <a-modal v-model:visible="isDeleteModalVisible" title="确认删除" @ok="handleDelete" @cancel="closeDeleteModal">
    <p>你确定要删除这门课程吗？{{ confirmDeleteCourseId }}</p>
  </a-modal>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { UserOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';
import { getAllCategory, getAllCoursesTeacher, updateCourseTeacher } from "@/apis/course.js";
import { useRouter } from "vue-router";

const router = useRouter();

// 定义响应式变量和状态
const hasbutton = ref(false);
const state = ref({
  selectedRowKeys: [], // 选中的行
  loading: false, // 加载状态
});

// 计算属性，判断是否有选中
const hasSelected = computed(() => {
  return state.value.selectedRowKeys.length > 0;
});

// 监听selectedRowKeys的变化
watch(() => state.value.selectedRowKeys, (newVal, oldVal) => {
  hasbutton.value = state.value.selectedRowKeys.length !== 0;
});

// 批量删除操作
const start = () => {
  state.value.loading = true;
  // 模拟异步请求完成后清空选中项
  setTimeout(() => {
    console.log('选中的课程ID: ', state.value.selectedRowKeys);
    state.value.loading = false;
    state.value.selectedRowKeys = [];
  }, 1000);
};

// 处理行选择变更
const onSelectChange = (selectedRowKeys) => {
  state.value.selectedRowKeys = selectedRowKeys;
};

// 响应式课程数据源
const courses = ref([]);

// 获取课程信息
const courseTeacher = async () => {
  const res = await getAllCoursesTeacher();
  courses.value = res.data;
};

// 组件挂载时获取数据
onMounted(() => {
  courseTeacher();
});

// 编辑和删除模态框的控制变量
const isEditModalVisible = ref(false);
const isDeleteModalVisible = ref(false);
const confirmDeleteCourseId = ref(null);

// 编辑课程的逻辑
const updateCourse = ref({});
const editCourse = (record) => {
  updateCourse.value = record;
  isEditModalVisible.value = true;
  console.log('编辑课程：', updateCourse.value);
};

// 处理编辑操作
const handleEdit = async () => {
  await updateCourseTeacher(updateCourse.value.courseId, updateCourse.value);
  updateCourse.value = {};
  isEditModalVisible.value = false;
};

// 关闭编辑模态框
const closeEditModal = () => {
  isEditModalVisible.value = false;
};

// 删除课程的逻辑
const deleteCourse = (courseId) => {
  confirmDeleteCourseId.value = courseId;
  isDeleteModalVisible.value = true;
};

// 处理删除操作
const handleDelete = () => {
  console.log('删除课程ID：', confirmDeleteCourseId.value);
  confirmDeleteCourseId.value = null;
  isDeleteModalVisible.value = false;
};

// 关闭删除模态框
const closeDeleteModal = () => {
  confirmDeleteCourseId.value = null;
  isDeleteModalVisible.value = false;
};

// 分类选项
const categoryOptions = ref([]);

// 获取所有分类
const allCategory = async () => {
  const res = await getAllCategory();
  categoryOptions.value = res.data;
};

// 组件挂载时获取分类
onMounted(() => {
  allCategory();
});

// 跳转到添加课程页面
const addCourse = () => {
  router.push({ name: 'add-course' });
};

//章节
const managerChapter = (courseId) => {
  console.log('跳转课程章节页',courseId)
  router.push({ name: 'chapter-list' , params: {courseId:courseId}});
};

// 监听分类变化并更新表格的列配置
watch(categoryOptions, () => {
  columns.find(col => col.key === 'categoryName').filters = categoryOptions.value.map(category => ({
    text: category.categoryName,
    value: category.categoryId,
  }));
});

// 定义表格列配置
const columns = [
  {
    title: '课程名称',
    dataIndex: 'title',
    key: 'title'
  },
  {
    title: '分类',
    dataIndex: 'categoryName',
    key: 'categoryName',
    filters: categoryOptions.value.map(category => ({
      text: category.categoryName,
      value: category.categoryId
    })),
    onFilter: (value, record) => record.categoryId === value
  },
  {
    title: '图片',
    dataIndex: 'image',
    key: 'image',
    slots: { customRender: 'image' }
  },
  {
    title: '教师',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '教师头像',
    dataIndex: 'teacherAvatar',
    key: 'teacherAvatar',
    slots: { customRender: 'teacherAvatar' }
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    sorter: (a, b) => a.price - b.price,
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt),
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    sorter: (a, b) => new Date(a.updatedAt) - new Date(b.updatedAt),
    sortDirections: ['ascend', 'descend']
  },
  {
    title: '操作',
    key: 'action',
    slots: { customRender: 'action' }
  }
];
</script>
